<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# " lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>frequentism-and-bayesianism-chs-iii | 绿萝间</title>
<link href="../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<link href="../assets/css/ipython.min.css" rel="stylesheet" type="text/css">
<link href="../assets/css/nikola_ipython.css" rel="stylesheet" type="text/css">
<meta name="theme-color" content="#5670d4">
<meta name="generator" content="Nikola (getnikola.com)">
<link rel="alternate" type="application/rss+xml" title="RSS" href="../rss.xml">
<link rel="canonical" href="https://muxuezi.github.io/posts/frequentism-and-bayesianism-chs-iii.html">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script><!--[if lt IE 9]><script src="../assets/js/html5.js"></script><![endif]--><meta name="author" content="Tao Junjie">
<link rel="prev" href="frequentism-and-bayesianism-chs-iv.html" title="frequentism-and-bayesianism-chs-iv" type="text/html">
<link rel="next" href="kivy-ch8-shaders-app.html" title="kivy-ch8-shaders-app" type="text/html">
<meta property="og:site_name" content="绿萝间">
<meta property="og:title" content="frequentism-and-bayesianism-chs-iii">
<meta property="og:url" content="https://muxuezi.github.io/posts/frequentism-and-bayesianism-chs-iii.html">
<meta property="og:description" content="频率主义 vs 贝叶斯主义 III：置信(Confidence)与可信(Credibility)，频率主义与科学，不能混为一谈¶








这个notebook出自Pythonic Perambulations的博文 . The content is BSD licensed.









这个系列共4个部分：中文版Part I  Part II  Part III  Part IV，">
<meta property="og:type" content="article">
<meta property="article:published_time" content="2015-06-24T13:43:03+08:00">
<meta property="article:tag" content="CHS">
<meta property="article:tag" content="Frequentism">
<meta property="article:tag" content="ipython">
<meta property="article:tag" content="Python">
</head>
<body>
<a href="#content" class="sr-only sr-only-focusable">Skip to main content</a>

<!-- Menubar -->

<nav class="navbar navbar-inverse navbar-static-top"><div class="container">
<!-- This keeps the margins nice -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="https://muxuezi.github.io/">

                <span id="blog-title">绿萝间</span>
            </a>
        </div>
<!-- /.navbar-header -->
        <div class="collapse navbar-collapse" id="bs-navbar" aria-expanded="false">
            <ul class="nav navbar-nav">
<li>
<a href="../archive.html">Archive</a>
                </li>
<li>
<a href="../categories/">Tags</a>
                </li>
<li>
<a href="../rss.xml">RSS feed</a>

                
            </li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
    <a href="frequentism-and-bayesianism-chs-iii.ipynb" id="sourcelink">Source</a>
    </li>

                
            </ul>
</div>
<!-- /.navbar-collapse -->
    </div>
<!-- /.container -->
</nav><!-- End of Menubar --><div class="container" id="content" role="main">
    <div class="body-content">
        <!--Body content-->
        <div class="row">
            
            
<article class="post-text h-entry hentry postpage" itemscope="itemscope" itemtype="http://schema.org/Article"><header><h1 class="p-name entry-title" itemprop="headline name"><a href="#" class="u-url">frequentism-and-bayesianism-chs-iii</a></h1>

        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                    Tao Junjie
            </span></p>
            <p class="dateline"><a href="#" rel="bookmark"><time class="published dt-published" datetime="2015-06-24T13:43:03+08:00" itemprop="datePublished" title="2015-06-24 13:43">2015-06-24 13:43</time></a></p>
            
        <p class="sourceline"><a href="frequentism-and-bayesianism-chs-iii.ipynb" id="sourcelink">Source</a></p>

        </div>
        

    </header><div class="e-content entry-content" itemprop="articleBody text">
    <div tabindex="-1" id="notebook" class="border-box-sizing">
    <div class="container" id="notebook-container">

<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="频率主义-vs-贝叶斯主义-III：置信(Confidence)与可信(Credibility)，频率主义与科学，不能混为一谈">频率主义 vs 贝叶斯主义 III：置信(Confidence)与可信(Credibility)，频率主义与科学，不能混为一谈<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E9%A2%91%E7%8E%87%E4%B8%BB%E4%B9%89-vs-%E8%B4%9D%E5%8F%B6%E6%96%AF%E4%B8%BB%E4%B9%89-III%EF%BC%9A%E7%BD%AE%E4%BF%A1(Confidence)%E4%B8%8E%E5%8F%AF%E4%BF%A1(Credibility)%EF%BC%8C%E9%A2%91%E7%8E%87%E4%B8%BB%E4%B9%89%E4%B8%8E%E7%A7%91%E5%AD%A6%EF%BC%8C%E4%B8%8D%E8%83%BD%E6%B7%B7%E4%B8%BA%E4%B8%80%E8%B0%88">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><em>这个notebook出自<a href="http://jakevdp.github.io">Pythonic Perambulations</a>的<a href="http://jakevdp.github.io/blog/2014/06/12/frequentism-and-bayesianism-3-confidence-credibility/">博文</a> . The content is BSD licensed.</em></p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><em>这个系列共4个部分：中文版<a href="http://muxuezi.github.io/posts/frequentism-and-bayesianism-chs">Part I</a>  <a href="http://muxuezi.github.io/posts/frequentism-and-bayesianism-chs-ii">Part II</a>  <a href="http://muxuezi.github.io/posts/frequentism-and-bayesianism-chs-iii">Part III</a>  <a href="http://muxuezi.github.io/posts/frequentism-and-bayesianism-chs-iv">Part IV</a>，英文版<a href="http://jakevdp.github.io/blog/2014/03/11/frequentism-and-bayesianism-a-practical-intro/">Part I</a>  <a href="http://jakevdp.github.io/blog/2014/06/06/frequentism-and-bayesianism-2-when-results-differ/">Part II</a>  <a href="http://jakevdp.github.io/blog/2014/06/12/frequentism-and-bayesianism-3-confidence-credibility/">Part III</a>  <a href="http://jakevdp.github.io/blog/2014/06/14/frequentism-and-bayesianism-4-bayesian-in-python/">Part IV</a></em></p>
<!-- TEASER_END -->
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在道格拉斯·亚当斯(Douglas Adams)的经典著作<em>《银河系漫游指南》</em>中，有一种超智慧生物(老鼠)建造了一部超级电脑，名深思(Deep Thought)，它们问超级电脑，“生命、宇宙以及任何事情的终极答案是什么”。经过750万年的计算，深思告诉老鼠的答案是：</p>
<p><strong>42</strong></p>
<p>失望的工程师们，折腾了一辈子就等到这样的回答，都呆住了。他们不停的追问深思更多的信息，最后深思说：“只要理解了问题的本质，你就能找到答案。”</p>
<p>也就是说，如果你不明白问题，那么答案也不会靠谱。</p>
<p>我觉得这个故事在科学统计工作中是个恰当的比喻。当估计未知参数时，频率论方法倾向于<strong>置信区间(confidence interval)</strong> (CI)，而贝叶斯理论则用<strong>可信范围(credible region)</strong> (CR)。尽管听起来没啥区别，但是在处理一些基本问题时，两者的差异变得至关重要。</p>
<p>就像道格拉斯·亚当斯宇宙中可怜的生命希望得到启示(enlightenment)，科学家们常常想运用频率主义获得正确结果，但这么做却忽略了科学的事实，那就是<strong>频率主义通常在回答错误的问题</strong>。这绝不是简单的纸上谈兵：只要我明白了观察数据，就可以从中获得正确的答案。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="置信-vs.-可信">置信 vs. 可信<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E7%BD%AE%E4%BF%A1-vs.-%E5%8F%AF%E4%BF%A1">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在<a href="http://jakevdp.github.io/blog/2014/03/11/frequentism-and-bayesianism-a-practical-intro/">第一节</a>中，我们讨论了频率主义与贝叶斯主义基本理论的差异：频率论认为概率是<strong>重复事件(假设)发生的频率</strong>；贝叶斯认为概率是<strong>数值的可信程度</strong>。更一般的结论是，频率论认为<strong>模型参数是固定的，而数据是随机的</strong>，而贝叶斯认为<strong>模型参数是随机的，而数据是固定的</strong>。</p>
<p>基础理论的差异影响两种方法选择模型参数数据边界的方式。因为差异很小，我就用一个简单的例子来论述一下频率论置信区间与贝叶斯可信范围的差异。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="例-1:-正态分布均值">例 1: 正态分布均值<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E4%BE%8B-1:-%E6%AD%A3%E6%80%81%E5%88%86%E5%B8%83%E5%9D%87%E5%80%BC">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>让我们用一个简单的例子来验证一下；此例同<a href="http://jakevdp.github.io/blog/2014/03/11/frequentism-and-bayesianism-a-practical-intro/">第一节</a> 中计算正态分布均值。 之前我们简单的分析了(频率论) 最大似然估计和(贝叶斯) 最大后验估计(posteriori estimates)；这里我们拓展一下：看看频率论置信区间与贝叶斯可信范围的差异。</p>
<p>问题是：你在观察一颗星星，你认为它的亮度是恒定的。为了简化，我们可以认为其亮度就是每秒到达我们望远镜的光量子数量。任何观察值都会有误差：虽然在此例中这些误差并不重要，但是我们假设观察值$x_i$服从正态分布，且标准差已知为$\sigma_x$。</p>
<p>对一组观察值，亮度置信水平95%(即2\sigma$)的置信区间是多少？</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="1.-频率论方法">1. 频率论方法<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#1.-%E9%A2%91%E7%8E%87%E8%AE%BA%E6%96%B9%E6%B3%95">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这个问题是频率论方法的经典案例，分析如下：</p>
<p>对任意$N$个值的$D = \{x_i\}_{i=1}^N$，分布的无偏估计均值$\mu$是</p>
$$
\bar{x} = \frac{1}{N}\sum_{i=1}^N x_i
$$<p><strong>样本分布(sampling)</strong>描述了均值估计的频率；通过中心极限定理(central limit theorem)我们可以得出样本分布是正态分布：</p>
$$
f(\bar{x}~||~\mu) \propto \exp\left[\frac{-(\bar{x} - \mu)^2}{2\sigma_\mu^2}\right]
$$<p>这里我们使用<strong>均值标准误差(standard error of the mean)</strong>,</p>
$$
\sigma_\mu = \sigma_x / \sqrt{N}
$$<p>中心极限定理告诉我们如果$N$足够大，任何分布都可以得到合理的近似值；如果分布呈正态分布，$N$就可以缩小到2。</p>
<p>让我们赶紧来验证这条经验，看看5组$10^6$个样本的均值情况：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>

<span class="n">N</span> <span class="o">=</span> <span class="mi">5</span>
<span class="n">Nsamp</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">**</span> <span class="mi">6</span>
<span class="n">sigma_x</span> <span class="o">=</span> <span class="mi">2</span>

<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">sigma_x</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="p">(</span><span class="n">Nsamp</span><span class="p">,</span> <span class="n">N</span><span class="p">))</span>
<span class="n">mu_samp</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">sig_samp</span> <span class="o">=</span> <span class="n">sigma_x</span> <span class="o">*</span> <span class="n">N</span> <span class="o">**</span> <span class="o">-</span><span class="mf">0.5</span>

<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="si">{0:.3f}</span><span class="s2"> should equal </span><span class="si">{1:.3f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">std</span><span class="p">(</span><span class="n">mu_samp</span><span class="p">),</span> <span class="n">sig_samp</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>0.894 should equal 0.894
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>如前所述，观察值的标准差等于$\sigma_x N^{-1/2}$。</p>
<p>从样本的正态分布中，我们可以轻易得出95%置信水平下的置信区间(想想那条钟形线)：</p>
$$
CI_{\mu} =  \left(\bar{x} - 2\sigma_\mu,~\bar{x} + 2\sigma_\mu\right)
$$
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们再看看：如果现在三个观察值标准差($\sigma_x$)是10。那么均值的95%置信区间是多少？</p>
<p>我们假设真实值是100:</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [2]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">true_B</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">sigma_x</span> <span class="o">=</span> <span class="mi">10</span>

<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">D</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="n">true_B</span><span class="p">,</span> <span class="n">sigma_x</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>[ 116.24345364   93.88243586   94.71828248]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>下面我们创建一个函数来算置信区间：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [3]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">scipy.special</span> <span class="k">import</span> <span class="n">erfinv</span>

<span class="k">def</span> <span class="nf">freq_CI_mu</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="n">sigma</span><span class="p">,</span> <span class="n">frac</span><span class="o">=</span><span class="mf">0.95</span><span class="p">):</span>
    <span class="sd">"""Compute the confidence interval on the mean"""</span>
    <span class="c1"># we'll compute Nsigma from the desired percentage</span>
    <span class="n">Nsigma</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">*</span> <span class="n">erfinv</span><span class="p">(</span><span class="n">frac</span><span class="p">)</span>
    <span class="n">mu</span> <span class="o">=</span> <span class="n">D</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
    <span class="n">sigma_mu</span> <span class="o">=</span> <span class="n">sigma</span> <span class="o">*</span> <span class="n">D</span><span class="o">.</span><span class="n">size</span> <span class="o">**</span> <span class="o">-</span><span class="mf">0.5</span>
    <span class="k">return</span> <span class="n">mu</span> <span class="o">-</span> <span class="n">Nsigma</span> <span class="o">*</span> <span class="n">sigma_mu</span><span class="p">,</span> <span class="n">mu</span> <span class="o">+</span> <span class="n">Nsigma</span> <span class="o">*</span> <span class="n">sigma_mu</span>

<span class="nb">print</span><span class="p">(</span><span class="s2">"95% Confidence Interval: [</span><span class="si">{0:.0f}</span><span class="s2">, </span><span class="si">{1:.0f}</span><span class="s2">]"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">freq_CI_mu</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="mi">10</span><span class="p">)))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>95% Confidence Interval: [90, 113]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>注意我们假设$\sigma_x$是已知的，这可以通过均值$\mu$来估计，但这里简单起见。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="2.-贝叶斯方法">2. 贝叶斯方法<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#2.-%E8%B4%9D%E5%8F%B6%E6%96%AF%E6%96%B9%E6%B3%95">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>用贝叶斯方法就得从贝叶斯定理开始：</p>
$$
P(\mu~|~D) = \frac{P(D~|~\mu)P(\mu)}{P(D)}
$$<p>我们对$\mu$用扁平先验(flat prior) (如，整个区间满足$P(\mu) \propto 1$) ，然后用似然估计</p>
$$
P(D~|~\mu) = \prod_{i=1}^N \frac{1}{\sqrt{2\pi\sigma_x^2}}\exp\left[\frac{(\mu - x_i)^2}{2\sigma_x^2}\right]
$$<p>计算乘积然后进行变换，可以得出</p>
$$
P(\mu~|~D) \propto \exp\left[\frac{-(\mu - \bar{x})^2}{2\sigma_\mu^2}\right]
$$<p>也可以看作是均值为$\bar{x}$，标准差为$\sigma_\mu$的正态分布。</p>
<p>也就是说，<strong>此例中$\mu$的贝叶斯后验结果等于频率论的样本分布均值$\mu$</strong>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>从后验结果可以计算出贝叶斯可信范围是95%可能的最短区间。看起来和频率论的置信区间很像：</p>
$$
CR_{\mu} =  \left(\bar{x} - 2\sigma_\mu,~\bar{x} + 2\sigma_\mu\right)
$$<p>我们设计一个函数来解叶斯可信范围：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [4]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">bayes_CR_mu</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="n">sigma</span><span class="p">,</span> <span class="n">frac</span><span class="o">=</span><span class="mf">0.95</span><span class="p">):</span>
    <span class="sd">"""Compute the credible region on the mean"""</span>
    <span class="n">Nsigma</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">*</span> <span class="n">erfinv</span><span class="p">(</span><span class="n">frac</span><span class="p">)</span>
    <span class="n">mu</span> <span class="o">=</span> <span class="n">D</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
    <span class="n">sigma_mu</span> <span class="o">=</span> <span class="n">sigma</span> <span class="o">*</span> <span class="n">D</span><span class="o">.</span><span class="n">size</span> <span class="o">**</span> <span class="o">-</span><span class="mf">0.5</span>
    <span class="k">return</span> <span class="n">mu</span> <span class="o">-</span> <span class="n">Nsigma</span> <span class="o">*</span> <span class="n">sigma_mu</span><span class="p">,</span> <span class="n">mu</span> <span class="o">+</span> <span class="n">Nsigma</span> <span class="o">*</span> <span class="n">sigma_mu</span>

<span class="nb">print</span><span class="p">(</span><span class="s2">"95% Credible Region: [</span><span class="si">{0:.0f}</span><span class="s2">, </span><span class="si">{1:.0f}</span><span class="s2">]"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">bayes_CR_mu</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="mi">10</span><span class="p">)))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>95% Credible Region: [90, 113]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="到底有啥区别？">到底有啥区别？<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E5%88%B0%E5%BA%95%E6%9C%89%E5%95%A5%E5%8C%BA%E5%88%AB%EF%BC%9F">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>上面的论证过程就是频率论置信区间与贝叶斯可信范围令人混乱的地方。在很多简单问题中，它们完全相等。但是我们必须清楚一点：<strong>数量相等，但是含义不同</strong>。</p>
<p>贝叶斯的概率反映我们相信的程度。所以当我们计算可信范围时，其实就是</p>
<blockquote>
<p>“对这个观察数据，真实值$\mu$会落在可信范围$CR_\mu$(固定的)内有95%的可能性”——贝叶斯主义</p>
</blockquote>
<p>而频率论认为$\mu$是一个固定值，而数据(以及所有数据派生的变量，包括置信区间的边界)是随机的。因此，频率论置信区间就是</p>
<blockquote>
<p>“当我们从这些数据(而不是那些数据)中计算$CI_\mu$时，有95%的可能性，真实值$\mu$会落在$CI_\mu$内”——频率主义</p>
</blockquote>
<p>注意区别：贝叶斯方法是对具有固定边界的参数值的概率表述(a statement of probability about the parameter value given fixed bounds)，而频率论方法是对固定参数值的边界的概率表述(a probability about the bounds given a fixed parameter value.)。</p>
<p>差别很小，但是我们下面会讲，这将造成极大差距。首先，让我们进一步用仿真方法来验证。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="确定贝叶斯可信范围">确定贝叶斯可信范围<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E7%A1%AE%E5%AE%9A%E8%B4%9D%E5%8F%B6%E6%96%AF%E5%8F%AF%E4%BF%A1%E8%8C%83%E5%9B%B4">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>确定贝叶斯可信范围，步骤如下：</p>
<ol>
<li>先验样本均值$\mu$是随机的</li>
<li>每个$\mu$有随机的数据集合</li>
<li>选取符合观察值的数据点</li>
<li>看看哪些$\mu$的值落在我们的可信范围内</li>
</ol>
<p>代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [5]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># first define some quantities that we need </span>
<span class="n">Nsamples</span> <span class="o">=</span> <span class="mf">2E7</span>
<span class="n">N</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>
<span class="n">sigma_x</span> <span class="o">=</span> <span class="mi">10</span>

<span class="c1"># if someone changes N, this could easily cause a memory error</span>
<span class="k">if</span> <span class="n">N</span> <span class="o">*</span> <span class="n">Nsamples</span> <span class="o">&gt;</span> <span class="mf">1E8</span><span class="p">:</span>
    <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">"Are you sure you want this many samples?"</span><span class="p">)</span>
    
<span class="c1"># eps tells us how close to D we need to be to consider</span>
<span class="c1"># it a matching sample. The value encodes the tradeoff</span>
<span class="c1"># between bias and variance of our simulation</span>
<span class="n">eps</span> <span class="o">=</span> <span class="mf">0.5</span>

<span class="c1"># Generate some mean values from the (flat) prior in a reasonable range</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">mu</span> <span class="o">=</span> <span class="mi">80</span> <span class="o">+</span> <span class="mi">40</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">(</span><span class="n">Nsamples</span><span class="p">)</span>

<span class="c1"># Generate data for each of these mean values</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="n">mu</span><span class="p">,</span> <span class="n">sigma_x</span><span class="p">,</span> <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">Nsamples</span><span class="p">))</span><span class="o">.</span><span class="n">T</span>

<span class="c1"># find data which matches our "observed" data</span>
<span class="n">x</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">D</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="n">i</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">all</span><span class="p">(</span><span class="nb">abs</span><span class="p">(</span><span class="n">x</span> <span class="o">-</span> <span class="n">D</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">eps</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"number of suitable samples: </span><span class="si">{0}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">i</span><span class="o">.</span><span class="n">sum</span><span class="p">()))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>number of suitable samples: 528
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [6]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Now we ask how many of these mu values fall in our credible region</span>
<span class="n">mu_good</span> <span class="o">=</span> <span class="n">mu</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="n">CR</span> <span class="o">=</span> <span class="n">bayes_CR_mu</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="n">within_CR</span> <span class="o">=</span> <span class="p">(</span><span class="n">CR</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">mu_good</span><span class="p">)</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">mu_good</span> <span class="o">&lt;</span> <span class="n">CR</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="nb">print</span> <span class="s2">"Fraction of means in Credible Region: </span><span class="si">{0:.3f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">within_CR</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">*</span> <span class="mf">1.</span> <span class="o">/</span> <span class="n">within_CR</span><span class="o">.</span><span class="n">size</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Fraction of means in Credible Region: 0.949
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>跟想的一样，95%可能的$\mu$的值落在我们的可信范围内。</p>
<p>这里，关键是明白哪些变量是随机的，哪些是固定的。在贝叶斯方法中，我们<strong>从我们的数据里计算出一个单独的可信范围</strong>，然后我们把它当作是<strong>$\mu$的多个随机点画出的图像</strong>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="确定频率论置信区间">确定频率论置信区间<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E7%A1%AE%E5%AE%9A%E9%A2%91%E7%8E%87%E8%AE%BA%E7%BD%AE%E4%BF%A1%E5%8C%BA%E9%97%B4">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>确定频率论置信区间有点小复杂，步骤如下：</p>
<ol>
<li>从唯一的真实值$\mu$定义的分布中画出数据集合</li>
<li>对每组数据，计算一个新的置信区间</li>
<li>看看哪些置信区间包含$\mu$</li>
</ol>
<p>代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [7]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># define some quantities we need</span>
<span class="n">N</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>
<span class="n">Nsamples</span> <span class="o">=</span> <span class="mf">1E4</span>
<span class="n">mu</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">sigma_x</span> <span class="o">=</span> <span class="mi">10</span>

<span class="c1"># Draw datasets from the true distribution</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="n">mu</span><span class="p">,</span> <span class="n">sigma_x</span><span class="p">,</span> <span class="p">(</span><span class="n">Nsamples</span><span class="p">,</span> <span class="n">N</span><span class="p">))</span>

<span class="c1"># Compute a confidence interval from each dataset</span>
<span class="n">CIs</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="n">freq_CI_mu</span><span class="p">(</span><span class="n">Di</span><span class="p">,</span> <span class="n">sigma_x</span><span class="p">)</span> <span class="k">for</span> <span class="n">Di</span> <span class="ow">in</span> <span class="n">x</span><span class="p">])</span>

<span class="c1"># find which confidence intervals contain the mean</span>
<span class="n">contains_mu</span> <span class="o">=</span> <span class="p">(</span><span class="n">CIs</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">mu</span><span class="p">)</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">mu</span> <span class="o">&lt;</span> <span class="n">CIs</span><span class="p">[:,</span> <span class="mi">1</span><span class="p">])</span>
<span class="nb">print</span> <span class="s2">"Fraction of Confidence Intervals containing the mean: </span><span class="si">{0:.3f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">contains_mu</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">*</span> <span class="mf">1.</span> <span class="o">/</span> <span class="n">contains_mu</span><span class="o">.</span><span class="n">size</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Fraction of Confidence Intervals containing the mean: 0.951
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>跟想的一样，95%置信区间包含μ的真实值。</p>
<p>同理，关键是明白哪些变量是随机的，哪些是固定的。我们把<strong>唯一值$\mu$</strong>看作是<strong>多个随机样本中的不同置信区间构成的</strong>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="讨论">讨论<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E8%AE%A8%E8%AE%BA">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们应该再一次提醒自己两者的差异：</p>
<ul>
<li>贝叶斯方法固定了可信范围，保证$\mu$95%的可能值落在可信范围内。</li>
<li>频率论方法固定了参数$\mu$， 保证95%置信区间包含$\mu$。</li>
</ul>
<p>比较上面两者的结论，我们会发现两者源自概率定义的区别。</p>
<ul>
<li>贝叶斯主义认为参数 (如$\mu$) 是随机变量，而频率主义认为是固定的。</li>
<li>贝叶斯主义认为观察值(如$D$)是固定的，而频率主义认为是随机变量。</li>
<li>贝叶斯主义认为参数约束(parameter constraints，如$CR_\mu$)是固定的，而频率主义认为(如$CI_\mu$)是是随机变量。</li>
</ul>
<p>很多简单问题都和上面的例子一样，置信水平和可信范围完全相等，所以这种差异一般不太重要。但是，科学计算不是简单问题；下面我们就看个复杂的例子，来感受一下这种差异。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="例-2：Jaynes截断分布(Truncated-Exponential)">例 2：Jaynes截断分布(Truncated Exponential)<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E4%BE%8B-2%EF%BC%9AJaynes%E6%88%AA%E6%96%AD%E5%88%86%E5%B8%83(Truncated-Exponential)">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>要找一个呈现两者差异的例子，我打算用E.T. Jaynes，一个20世纪的物理学家，做了大量统计工作。在他的书<em>Confidence Intervals vs. Bayesian Intervals</em> (<a href="http://bayes.wustl.edu/etj/articles/confidence.pdf">pdf</a>)中第15个例子，他用了一个截断分布。他是这么说的：</p>
<blockquote>
<p>一个设备，因为注入了一种防护性化学试剂(protective chemical inhibitor)，所以在$\theta$时间内运行正常；但是在$\theta$时间之后，化学试剂用光了，问题就出现了，而且失败次数呈指数分布。没有办法直接观察化学试剂消耗的情况；只能观察到失败的结果。从实际观察数据中，估计$\theta$时间以确保运行安全......</p>
</blockquote>
<p>从下面的模型可以获得一个数据$D$：</p>
$$
p(x~|~\theta) = \left\{
\begin{array}{lll}
\exp(\theta - x) &amp;,&amp; x &gt; \theta\\
0                &amp;,&amp; x &lt; \theta
\end{array}
\right\}
$$<p>这里$p(x~|~\theta)$表示时间$x$失败的概率，化学试剂可用时间$\theta$。
观察数据$D = \{x_i\}$，我们的目标是估计$\theta$。</p>
<p>我们先为$\theta=10$画个图看看：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [8]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>

<span class="k">def</span> <span class="nf">p</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">theta</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">&gt;</span> <span class="n">theta</span><span class="p">)</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">theta</span> <span class="o">-</span> <span class="n">x</span><span class="p">)</span>

<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">p</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">10</span><span class="p">),</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">0.3</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylim</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mf">1.2</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s1">'x'</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s1">'p(x)'</span><span class="p">);</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>


<div class="output_png output_subarea ">
<img src="%0AAAALEgAACxIB0t1+/AAAG0pJREFUeJzt3Xlwm/dh5vEvQIIgCVC8dFNy5Dh2Irm2ctiO28Y10xx1%0AMm087e4k9aZtju5uZmecPWeTJjtTK9Npptkm02zHXcebTTLp5nBcb9rYiRNvfMCxVdvxSSu6ad0X%0AZZE6SEmkeGD/eEEJoniAFF++wIvvZwZDHC/AxzKIB+/7+73vC5IkSZIkSZIkSZIkSZIkSVLkvgn0%0AAJumePyjQBfwKrARuH6BckmSFtgtwNuYuhB+HWguXL8NeHYhQkmSorGGqQuhWCtwINwokqSpJKMO%0AUORPgYejDiFJCs8aZl5DeDewhWAtQZIUgdqoAxAMJH+dYAzh+GQLrF+/Pt/V1bWgoSQpBrqAt5a6%0AcNSbjK4Afgj8EdA91UJdXV3k8/mKvdx1112RZ6jW/JWc3fzRXyo9P7B+Nh/IYa8hfB+4FVgM7Afu%0AAlKFx+4F/pxgM9E9hfuGgZtCziRJmkTYhXDHDI//68JFkhSxqDcZVYXOzs6oI1yWSs5fydnB/FGr%0A9PyzlYg6QInyhe1hkqQSJRIJmMXnvGsIkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAk%0AFVgIkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAkFVgI%0AkiTAQpAkFVgIkiTAQpAkFVgIkiTAQpAkFYRdCN8EeoBN0yzzt8BOoAt4W8h5JElTCLsQvgXcNs3j%0AHwTeBFwN/FvgnpDzSJKmEHYhPAUcn+bxDwHfLlx/DmgBloWcSZI0iajHEDqA/UW3DwCrIsoiSVUt%0A6kIASEy4nY8khSRVudqIf/9BYHXR7VWF+y6xYcOG89c7Ozvp7OwMM5ckVZxcLkcul5vz8yd+Ow/D%0AGuAh4LpJHvsgcGfh583AVws/J8rn8644aPaeeC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fNbjTR3DxKcsOaN%0ABOda+HS0cSRJUfgTgnMFQ7Cm/SzlfXhkSZIkSZIkSZIkSZIkSZIkSZIkSZKk+fX/AeH4pZd+nuUh%0AAAAAAElFTkSuQmCC">
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在我们的观察数据是$D = \{10, 12, 15\}$，我们想从这些数据中推断$\theta$。下面用四种方法来探索。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="1.-常识(Common-Sense)方法">1. 常识(Common Sense)方法<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#1.-%E5%B8%B8%E8%AF%86(Common-Sense)%E6%96%B9%E6%B3%95">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我认为：遇到问题，计算之前，先想想怎么下手，并猜一猜结果。我们现在开始。想想这个问题，从概率分布的截断可以得出一个简单的观察结果：<strong>$\theta$必须小于观察值的最小值</strong>。</p>
<p>这是显而易见的：看到一个小于$\theta$的观察值概率为0。因此，假如我们假设正确，那么一个$\theta$大于任何观察值的模型是不可能出现的。贝叶斯主义和频率主义的基本假设都是模型正确，因此我们可以直接写出常识条件：</p>
$$
\theta &lt; \min(D)
$$<p>或者，特别地，$D = \{10, 12, 15\}$,</p>
$$
\theta &lt; 10
$$<p>这组数据中，$\theta$的每一个合理约束都应该满足以上条件。带着这条规则，我们继续用贝叶斯主义和频率主义进行定量分析。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="2.-频率论方法-#1：正态分布近似的样本分布">2. 频率论方法 #1：正态分布近似的样本分布<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#2.-%E9%A2%91%E7%8E%87%E8%AE%BA%E6%96%B9%E6%B3%95-#1%EF%BC%9A%E6%AD%A3%E6%80%81%E5%88%86%E5%B8%83%E8%BF%91%E4%BC%BC%E7%9A%84%E6%A0%B7%E6%9C%AC%E5%88%86%E5%B8%83">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在频率论方法中，我们要计算$\theta$的置信区间，可以通过观察值的计算均值开始</p>
$$
\begin{array}{ll}
E(x) &amp;= \int_0^\infty xp(x)dx\\
     &amp;= \theta + 1
     \end{array}
$$<p>因此，用样本均值作为$E(x)$的点估计值， 就得到$\theta$的无偏估计(unbiased estimator)</p>
$$
\hat{\theta} = \frac{1}{N} \sum_{i=1}^N x_i - 1
$$<p>指数分布的标准差为1，所以当$N$组够大，我们就可以用均值的标准差来表示$\hat{\theta}$的样本分布情况，将满足方差$\sigma^2 = 1 / N$的正态分布。因此，我们可以写出95% (就是2$\sigma$)的置信区间为</p>
$$
CI_{\rm large~N} = \left(\hat{\theta} - 2 N^{-1/2},~\hat{\theta} + 2 N^{-1/2}\right)
$$<p>写成函数代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">scipy.special</span> <span class="k">import</span> <span class="n">erfinv</span>

<span class="k">def</span> <span class="nf">approx_CI</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="n">sig</span><span class="o">=</span><span class="mf">0.95</span><span class="p">):</span>
    <span class="sd">"""Approximate truncated exponential confidence interval"""</span>
    <span class="c1"># use erfinv to convert percentage to number of sigma</span>
    <span class="n">Nsigma</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">*</span> <span class="n">erfinv</span><span class="p">(</span><span class="n">sig</span><span class="p">)</span>
    <span class="n">D</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>
    <span class="n">N</span> <span class="o">=</span> <span class="n">D</span><span class="o">.</span><span class="n">size</span>
    <span class="n">theta_hat</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">D</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span>
    <span class="k">return</span> <span class="p">[</span><span class="n">theta_hat</span> <span class="o">-</span> <span class="n">Nsigma</span> <span class="o">/</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">N</span><span class="p">),</span>
            <span class="n">theta_hat</span> <span class="o">+</span> <span class="n">Nsigma</span> <span class="o">/</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">N</span><span class="p">)]</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [10]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">D</span> <span class="o">=</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">15</span><span class="p">]</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"approximate CI: (</span><span class="si">{0:.1f}</span><span class="s2">, </span><span class="si">{1:.1f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">approx_CI</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>approximate CI: (10.2, 12.5)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这里有个问题。通过我们简单的常识，我们认为$\theta$不可能大于10，但是上面的范围依然是95%置信区间。可能观察数据应该太少了： 上面的计算应该基于一个大的$N$ ，而我们用的是一个很小的$N = 3$。我们用更多的计算来试试看：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="3.-频率论方法-#2：精确的样本分布">3. 频率论方法 #2：精确的样本分布<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#3.-%E9%A2%91%E7%8E%87%E8%AE%BA%E6%96%B9%E6%B3%95-#2%EF%BC%9A%E7%B2%BE%E7%A1%AE%E7%9A%84%E6%A0%B7%E6%9C%AC%E5%88%86%E5%B8%83">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>用精确的样本分布计算置信区间需要费一番功夫：</p>
<p>对较小的$N$，正态分布近似是不能用的，我们必须用真实的样本分布计算置信区间，就是$N$个变量的均值的分布取决于$p(\theta)$。随机变量的和服从单个变量的分布的卷积(convolution)，因此我们可以看看<a href="http://en.wikipedia.org/wiki/Convolution_theorem">卷积理论(convolution theorem)</a>，再使用<a href="http://en.wikipedia.org/wiki/Characteristic_function_(probability_theory">特征方程(characteristic functions)</a>，来找到取决于$p(x~|~\theta)$的$N$个变量的和样本分布：</p>
$$
f(\theta~|~D) \propto
\left\{
\begin{array}{lll}
z^{N - 1}\exp(-z) &amp;,&amp; z &gt; 0\\
0 &amp;,&amp; z &lt; 0
\end{array}
\right\}
;~ z = N(\hat{\theta} + 1 - \theta)
$$
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>要计算95%置信区间，我们要算累计分别函数：求$f(\theta~|~D)$从$0$到$\theta$的积分。如果我们使用<a href="http://en.wikipedia.org/wiki/Incomplete_gamma_function">不完全Gamma方程(incomplete gamma function)</a>会容易点：</p>
$$
\Gamma(a, x) = \int_x^\infty t^{a - 1}e^{-t} dt
$$<p>看起来和$f(\theta)$非常的像。</p>
<p>算出积分，我们就可以得出累计分布函数是：</p>
$$
F(\theta~|~D) = \frac{1}{\Gamma(N)}\left[ \Gamma\left(N, \max[0, N(\hat{\theta} + 1 - \theta)]\right) - \Gamma\left(N,~N(\hat{\theta} + 1)\right)\right]
$$
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>一个连续的95%置信区间$(\theta_1, \theta_2)$满足下列方程：</p>
$$
F(\theta_2~|~D) - F(\theta_1~|~D) = 0.95
$$<p>实际上有无限多组解，我们要的是最短的区间。我们可以增加两边概率密度相等的约束：</p>
$$
f(\theta_2~|~D) = f(\theta_1~|~D)
$$<p>(Jaynes认为这一条确保区间是最短的，但是我(作者)不明白怎么证明)。其实因为正态分布钟形曲线的对称性，如果要达到同样的95%置信水平(概率)，也就是同样的面积，则越往中间则面积越大，区间越小。那么对称的区间的长度一定比同面积的非对称区间的长度都短。</p>
<p>解决这两个非线性方程的系统就可以得出置信区间。计算过程如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [11]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">scipy.special</span> <span class="k">import</span> <span class="n">gammaincc</span>
<span class="kn">from</span> <span class="nn">scipy</span> <span class="k">import</span> <span class="n">optimize</span>


<span class="k">def</span> <span class="nf">exact_CI</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="n">frac</span><span class="o">=</span><span class="mf">0.95</span><span class="p">):</span>
    <span class="sd">"""Exact truncated exponential confidence interval"""</span>
    <span class="n">D</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>
    <span class="n">N</span> <span class="o">=</span> <span class="n">D</span><span class="o">.</span><span class="n">size</span>
    <span class="n">theta_hat</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">D</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">theta</span><span class="p">,</span> <span class="n">D</span><span class="p">):</span>
        <span class="n">z</span> <span class="o">=</span> <span class="n">theta_hat</span> <span class="o">+</span> <span class="mi">1</span> <span class="o">-</span> <span class="n">theta</span>
        <span class="k">return</span> <span class="p">(</span><span class="n">z</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="o">*</span> <span class="n">z</span> <span class="o">**</span> <span class="p">(</span><span class="n">N</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="n">N</span> <span class="o">*</span> <span class="n">z</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">F</span><span class="p">(</span><span class="n">theta</span><span class="p">,</span> <span class="n">D</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">gammaincc</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">maximum</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">N</span> <span class="o">*</span> <span class="p">(</span><span class="n">theta_hat</span> <span class="o">+</span> <span class="mi">1</span> <span class="o">-</span> <span class="n">theta</span><span class="p">)))</span> <span class="o">-</span> <span class="n">gammaincc</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">N</span> <span class="o">*</span> <span class="p">(</span><span class="n">theta_hat</span> <span class="o">+</span> <span class="mi">1</span><span class="p">))</span>
    
    <span class="k">def</span> <span class="nf">eqns</span><span class="p">(</span><span class="n">CI</span><span class="p">,</span> <span class="n">D</span><span class="p">):</span>
        <span class="sd">"""Equations which should be equal to zero"""</span>
        <span class="n">theta1</span><span class="p">,</span> <span class="n">theta2</span> <span class="o">=</span> <span class="n">CI</span>
        <span class="k">return</span> <span class="p">(</span><span class="n">F</span><span class="p">(</span><span class="n">theta2</span><span class="p">,</span> <span class="n">D</span><span class="p">)</span> <span class="o">-</span> <span class="n">F</span><span class="p">(</span><span class="n">theta1</span><span class="p">,</span> <span class="n">D</span><span class="p">)</span> <span class="o">-</span> <span class="n">frac</span><span class="p">,</span>
                <span class="n">f</span><span class="p">(</span><span class="n">theta2</span><span class="p">,</span> <span class="n">D</span><span class="p">)</span> <span class="o">-</span> <span class="n">f</span><span class="p">(</span><span class="n">theta1</span><span class="p">,</span> <span class="n">D</span><span class="p">))</span>
    
    <span class="n">guess</span> <span class="o">=</span> <span class="n">approx_CI</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="mf">0.68</span><span class="p">)</span> <span class="c1"># use 1-sigma interval as a guess</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">optimize</span><span class="o">.</span><span class="n">root</span><span class="p">(</span><span class="n">eqns</span><span class="p">,</span> <span class="n">guess</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">D</span><span class="p">,))</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">result</span><span class="o">.</span><span class="n">success</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">"warning: CI result did not converge!"</span>
    <span class="k">return</span> <span class="n">result</span><span class="o">.</span><span class="n">x</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>为了保证合理性(sanity check)，确保精确的与近似的置信区间在大量数据下是一致的：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [12]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">Dlarge</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">"approx: (</span><span class="si">{0:.3f}</span><span class="s2">, </span><span class="si">{1:.3f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">approx_CI</span><span class="p">(</span><span class="n">Dlarge</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">"exact: (</span><span class="si">{0:.3f}</span><span class="s2">, </span><span class="si">{1:.3f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">exact_CI</span><span class="p">(</span><span class="n">Dlarge</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>approx: (9.409, 9.584)
exact: (9.408, 9.584)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>确实，在较大的$N$解出的精确区间与近似区间一致，这让我们确信我们的计算是正确的。</p>
<p>让我们回到之前3个点的数据集看看结果：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [13]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"approximate CI: (</span><span class="si">{0:.1f}</span><span class="s2">, </span><span class="si">{1:.1f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">approx_CI</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"exact CI:       (</span><span class="si">{0:.1f}</span><span class="s2">, </span><span class="si">{1:.1f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">exact_CI</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>approximate CI: (10.2, 12.5)
exact CI:       (10.2, 12.2)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>精确的置信区间与近似置信区间稍有不同，但是反映了同样的问题：<strong>我们从常识推断$\theta$不能大于10，而95%的置信区间完全处于大于10的区间内</strong>。这个置信区间看起来不太靠谱。</p>
<p>后面我们会仔细研究，现在我们看看贝叶斯的解决方法是不是更好。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="4.-贝叶斯可信范围">4. 贝叶斯可信范围<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#4.-%E8%B4%9D%E5%8F%B6%E6%96%AF%E5%8F%AF%E4%BF%A1%E8%8C%83%E5%9B%B4">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>首先我们用贝叶斯定理：</p>
$$
p(\theta~|~D) = \frac{p(D~|~\theta)p(\theta)}{P(D)}
$$<p>用一个常量的$p(\theta)$，它的似然估计为</p>
$$
p(D~|~\theta) = \prod_{i=1}^N p(x~|~\theta)
$$<p>可以得出</p>
$$
p(\theta~|~D) \propto \left\{
\begin{array}{lll}
N\exp\left[N(\theta - \min(D))\right] &amp;,&amp; \theta &lt; \min(D)\\
0                &amp;,&amp; \theta &gt; \min(D)
\end{array}
\right\}
$$<p>其中，$\min(D)$是$D$的最小值， 之所以出现是因为$p(x~|~\theta)$的截断。
因为$p(\theta~|~D)$会指数增长到截断位置(cutoff)，所以最短的95%置信区间$(\theta_1, \theta_2)$就是</p>
$$
\theta_2 = \min(D)
$$<p>而$\theta_1$就是下面方程的解</p>
$$
\int_{\theta_1}^{\theta_2} N\exp[N(\theta - \theta_2)]d\theta = f
$$<p>算积分可以求解方程</p>
$$
\theta_1 = \theta_2 + \frac{\log(1 - f)}{N}
$$<p>解法如下所示：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [14]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">bayes_CR</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="n">frac</span><span class="o">=</span><span class="mf">0.95</span><span class="p">):</span>
    <span class="sd">"""Bayesian Credibility Region"""</span>
    <span class="n">D</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>
    <span class="n">N</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">D</span><span class="o">.</span><span class="n">size</span><span class="p">)</span>
    <span class="n">theta2</span> <span class="o">=</span> <span class="n">D</span><span class="o">.</span><span class="n">min</span><span class="p">()</span>
    <span class="n">theta1</span> <span class="o">=</span> <span class="n">theta2</span> <span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="mf">1.</span> <span class="o">-</span> <span class="n">frac</span><span class="p">)</span> <span class="o">/</span> <span class="n">N</span>
    <span class="k">return</span> <span class="n">theta1</span><span class="p">,</span> <span class="n">theta2</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>贝叶斯方法就搞定了，下面我们来比较一下四种方法：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [15]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"common sense:         theta &lt; </span><span class="si">{0:.1f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">min</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"frequentism (approx): 95% CI = (</span><span class="si">{0:.1f}</span><span class="s2">, </span><span class="si">{1:.1f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">approx_CI</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"frequentism (exact):  95% CI = (</span><span class="si">{0:.1f}</span><span class="s2">, </span><span class="si">{1:.1f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">exact_CI</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Bayesian:             95% CR = (</span><span class="si">{0:.1f}</span><span class="s2">, </span><span class="si">{1:.1f}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">bayes_CR</span><span class="p">(</span><span class="n">D</span><span class="p">)))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>common sense:         theta &lt; 10.0
frequentism (approx): 95% CI = (10.2, 12.5)
frequentism (exact):  95% CI = (10.2, 12.2)
Bayesian:             95% CR = (9.0, 10.0)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们会发现贝叶斯方法与常识是一致的，而频率论不靠谱。问题就是<strong>频率主义一直回答错误的问题</strong>。下面我会详谈，首先我们通过仿真来验证CI和CR的正确性。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="数值方法验证">数值方法验证<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E6%95%B0%E5%80%BC%E6%96%B9%E6%B3%95%E9%AA%8C%E8%AF%81">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>为了消除对数学的担忧，我想重复之前做过的事情，说明<em>前面的置信区间其实是正确的</em>。我们将用前面提到的方法，假设这个<em>真实</em>的$\theta$和具有同样分布的样本数据：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [16]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="k">import</span> <span class="n">expon</span>

<span class="n">Nsamples</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="n">N</span> <span class="o">=</span> <span class="mi">3</span>
<span class="n">theta</span> <span class="o">=</span> <span class="mi">10</span>

<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">expon</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span><span class="o">.</span><span class="n">rvs</span><span class="p">((</span><span class="n">Nsamples</span><span class="p">,</span> <span class="n">N</span><span class="p">))</span>
<span class="n">CIs</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="n">exact_CI</span><span class="p">(</span><span class="n">Di</span><span class="p">)</span> <span class="k">for</span> <span class="n">Di</span> <span class="ow">in</span> <span class="n">data</span><span class="p">])</span>

<span class="c1"># find which confidence intervals contain the mean</span>
<span class="n">contains_theta</span> <span class="o">=</span> <span class="p">(</span><span class="n">CIs</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">theta</span><span class="p">)</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">theta</span> <span class="o">&lt;</span> <span class="n">CIs</span><span class="p">[:,</span> <span class="mi">1</span><span class="p">])</span>
<span class="nb">print</span> <span class="s2">"Fraction of Confidence Intervals containing theta: </span><span class="si">{0:.3f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">contains_theta</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">*</span> <span class="mf">1.</span> <span class="o">/</span> <span class="n">contains_theta</span><span class="o">.</span><span class="n">size</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Fraction of Confidence Intervals containing theta: 0.953
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>按照频率主义的观点，计算出来的置信区间的95%可能是包含真实值的。我们计算置信区间的程序实际是正确的：数据其实是在另外的5%里面。但是：<strong>我们从数据本身出发，发现我们真处于让CI失败的5%数据中</strong>。标准的频率论置信区间理论忽略了这样的事实，那就是在处理任何问题时，常识都应该让你停止对置信区间的盲目依赖。</p>
<p>让我们检查一下贝叶斯可信区域的测试结果：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [17]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="n">N</span> <span class="o">=</span> <span class="mf">1E7</span>
<span class="n">eps</span> <span class="o">=</span> <span class="mf">0.1</span>

<span class="n">theta</span> <span class="o">=</span> <span class="mi">9</span> <span class="o">+</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">(</span><span class="n">N</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="p">(</span><span class="n">theta</span> <span class="o">+</span> <span class="n">expon</span><span class="p">()</span><span class="o">.</span><span class="n">rvs</span><span class="p">((</span><span class="mi">3</span><span class="p">,</span> <span class="n">N</span><span class="p">)))</span><span class="o">.</span><span class="n">T</span>
<span class="n">data</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">D</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="n">i_good</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">all</span><span class="p">(</span><span class="nb">abs</span><span class="p">(</span><span class="n">data</span> <span class="o">-</span> <span class="n">D</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">eps</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>

<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of good samples: </span><span class="si">{0}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">i_good</span><span class="o">.</span><span class="n">sum</span><span class="p">()))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of good samples: 65
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [18]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">theta_good</span> <span class="o">=</span> <span class="n">theta</span><span class="p">[</span><span class="n">i_good</span><span class="p">]</span>
<span class="n">theta1</span><span class="p">,</span> <span class="n">theta2</span> <span class="o">=</span> <span class="n">bayes_CR</span><span class="p">(</span><span class="n">D</span><span class="p">)</span>

<span class="n">within_CR</span> <span class="o">=</span> <span class="p">(</span><span class="n">theta1</span> <span class="o">&lt;</span> <span class="n">theta_good</span><span class="p">)</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">theta_good</span> <span class="o">&lt;</span> <span class="n">theta2</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Fraction of thetas in Credible Region: </span><span class="si">{0:.3f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">within_CR</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">*</span> <span class="mf">1.</span> <span class="o">/</span> <span class="n">within_CR</span><span class="o">.</span><span class="n">size</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Fraction of thetas in Credible Region: 0.954
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>看，确实如此，~95%的$\theta$的数值落在我们通过单个数据样本计算的可信范围内。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="频率主义回答错误问题">频率主义回答错误问题<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E9%A2%91%E7%8E%87%E4%B8%BB%E4%B9%89%E5%9B%9E%E7%AD%94%E9%94%99%E8%AF%AF%E9%97%AE%E9%A2%98">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在例二中，我们演示了频率论方法是<em>技术正确的</em>，但是它违背我们的常识。到底是咋回事儿？</p>
<p>问题的关键是：<strong>频率论置信区间给出正确答案的同时，通常是在回答错误的问题</strong>。错误的问题就是频率论的<em>基础</em>——概率定义。</p>
<p>回想上面我对置信区间和可信范围的论述。贝叶斯主义说：</p>
<blockquote>
<p>"从观察到的数据来看，$\theta$的真实值有95%的可能性落在可信范围内" - 贝叶斯主义</p>
</blockquote>
<p>而频率主义说：</p>
<blockquote>
<p>"当我用这组数据计算置信区间时，$\theta$有95%的可能在区间内" - 频率主义</p>
</blockquote>
<p>想想看，假如你发现设备宕机了3次，你想估计$\theta$。我认为"这种数据"不是你的目标：你应该关心的是你可以从<strong>这三次观察</strong>中发现什么问题，而非观察的整个假设空间(not the entire hypothetical space of observations like them)。如前所述，如果你步频率论后尘去考虑"这种数据"，你就置身获得答案的绝境，从你观察到的特殊情况中得不到任何价值。</p>
<p>假如你想改变知道<em>从你观察到的数据中</em>，频率论置信区间可以告诉你什么。这就是答案：</p>
<blockquote>
<p>"<em>从观察到的数据来看</em>，$\theta$的真实值要么在置信区间里，要么不在里面" - 频率主义</p>
</blockquote>
<p>这就是对你观察到的<strong>这些数据</strong>置信区间想说的，也能说的内容。当然，这看起来有点啰嗦，那么精简一点的说法就是:</p>
<blockquote>
<p>"<em>从观察到的数据来看</em>，我无法确定$\theta$值的范围" - 频率主义</p>
</blockquote>
<p>如果你想从你观察到的数据中得到答案，频率主义是不靠谱的。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="再坚持下哈...-这是不是有点过分苛责？">再坚持下哈... 这是不是有点过分苛责？<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E5%86%8D%E5%9D%9A%E6%8C%81%E4%B8%8B%E5%93%88...-%E8%BF%99%E6%98%AF%E4%B8%8D%E6%98%AF%E6%9C%89%E7%82%B9%E8%BF%87%E5%88%86%E8%8B%9B%E8%B4%A3%EF%BC%9F">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这么说可能有点苛刻，但是我想说这不是信口雌黄；这是关于频率主义的哲学立场和置信区间的定义的一个不争的事实。如果你想从观察到的数据中获得靠谱的结论(如置信区间和相关系数$p$值)，频率主义是相当不靠谱的。</p>
<p>不幸的是，整天在用频率论方法的很多人都没有意识到这些。我从天文学的案例中指明了这些，但是我并非要让大家难堪(他们很容易知道现在你要找什么)。很多科学家把置信区间当作贝叶斯可信范围，<strong>但这明显是错的</strong>。统计学外行可能会原谅对这一观点的忽略，但是专业的统计学家们也经常错误地解释置信区间。</p>
<p>我认为这个错误如此普遍的理由，是因为在很多小问题(如前所述)中，置信区间与可信范围恰好一致。这时，频率主义正确地回答了你的问题，<strong>但是仅仅因为贝叶斯主义也给出了相同的结果</strong>。(如果贝叶斯的结果不一样，频率论就错了。)</p>
<p>我绝非第一个这么说的人。物理学家<a href="http://en.wikipedia.org/wiki/Edwin_Thompson_Jaynes">E.T. Jaynes</a>是公认的贝叶斯捍卫者； 我的一个灵感来自他1976的论文<em>Confidence Intervals vs. Bayesian Intervals</em> (<a href="http://bayes.wustl.edu/etj/articles/confidence.pdf">pdf</a>)。最近，持同样观点的，还有统计学家与博主<a href="http://wmbriggs.com/">W.M. Briggs</a> 在arX发表的博文<a href="http://arxiv.org/abs/1201.2590"><em>再也别给非统计学人士讲频率主义了(It's Time To Stop Teaching Frequentism to Non-Statisticians)</em></a>。还有<a href="http://en.wikipedia.org/wiki/Leonard_Jimmie_Savage">Savage</a>， <a href="http://en.wikipedia.org/wiki/Jerome_Cornfield">Cornfield</a>，以及20世纪的贝叶斯实践者们大量的著作言论。</p>
<p>那么，你还想用置信区间吗？可能在多个数据获取可以实现的情况下(如分析赌博赔率)，频率主义是有意义的。但是在大多数科学应用中，当你关心的是目前获取的数据可以告诉我们什么时，<strong>频率主义只会回答错误的问题</strong>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="本文的寓意：频率主义不能与科学混为一谈">本文的寓意：频率主义不能与科学混为一谈<a class="anchor-link" href="frequentism-and-bayesianism-chs-iii.html#%E6%9C%AC%E6%96%87%E7%9A%84%E5%AF%93%E6%84%8F%EF%BC%9A%E9%A2%91%E7%8E%87%E4%B8%BB%E4%B9%89%E4%B8%8D%E8%83%BD%E4%B8%8E%E7%A7%91%E5%AD%A6%E6%B7%B7%E4%B8%BA%E4%B8%80%E8%B0%88">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>本文的寓意就是频率主义不能与科学混为一谈。<em>在科学工作中，你要质疑对频率论的置信区间和p值的使用</em>。在科学研究时，置信区间和相关系数p值，为错误的问题提供了正确的答案。尤其是当你发现有人说95%置信区间就是对目标参数95%的确定时，<strong>不要相信他们的解释和结论</strong>。如果你是论文审稿人,<strong>直接拒绝</strong>。他们的数据不能支撑其结论。</p>
<p>如果你坚持到这里，我非常感谢你！我希望这些解释成功地阐述了频率主义与贝叶斯主义的哲学假设对实际的数据分析和解释的差异。如果本文让一个研究者不再用频率论置信区间做科学研究，那么我就认为我成功l。</p>
<p><small>
这篇博客是IPython notebook写的。可以[下载](http://jakevdp.github.io/downloads/notebooks/FreqBayes3.ipynb)，或者看[nbviewer](http://nbviewer.ipython.org/url/jakevdp.github.io/downloads/notebooks/FreqBayes3.ipynb)静态网页。
十分感谢David W. Hogg对本文提出的建议。
</small></p>

</div>
</div>
</div>
    </div>
  </div>

    </div>
    <aside class="postpromonav"><nav><ul itemprop="keywords" class="tags">
<li><a class="tag p-category" href="../categories/chs.html" rel="tag">CHS</a></li>
            <li><a class="tag p-category" href="../categories/frequentism.html" rel="tag">Frequentism</a></li>
            <li><a class="tag p-category" href="../categories/ipython.html" rel="tag">ipython</a></li>
            <li><a class="tag p-category" href="../categories/python.html" rel="tag">Python</a></li>
        </ul>
<ul class="pager hidden-print">
<li class="previous">
                <a href="frequentism-and-bayesianism-chs-iv.html" rel="prev" title="frequentism-and-bayesianism-chs-iv">Previous post</a>
            </li>
            <li class="next">
                <a href="kivy-ch8-shaders-app.html" rel="next" title="kivy-ch8-shaders-app">Next post</a>
            </li>
        </ul></nav></aside><script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script><script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script></article>
</div>
        <!--End of body content-->

        <footer id="footer">
            Contents © 2017         <a href="mailto:muxuezi@gmail.com">Tao Junjie</a> - Powered by         <a href="https://getnikola.com" rel="nofollow">Nikola</a>         
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0">
<img alt="Creative Commons License BY-NC-SA" style="border-width:0; margin-bottom:12px;" src="http://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png"></a>
            
        </footer>
</div>
</div>


            <script src="../assets/js/all-nocdn.js"></script><script>$('a.image-reference:not(.islink) img:not(.islink)').parent().colorbox({rel:"gal",maxWidth:"100%",maxHeight:"100%",scalePhotos:true});</script><!-- fancy dates --><script>
    moment.locale("en");
    fancydates(0, "YYYY-MM-DD HH:mm");
    </script><!-- end fancy dates --><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51330059-1', 'auto');
  ga('send', 'pageview');

</script>
</body>
</html>
